package com.choudou5.nlp.util;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.nlp.AipNlp;
import com.choudou5.nlp.config.AppKeyBean;
import com.choudou5.nlp.consts.AnalysisConsts;
import com.choudou5.solr.util.LogDeBugUtil;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.util.cache.CacheFactory;
import com.choudou5.solr.util.cache.impl.LRUCache;
import com.choudou5.solr.util.http.HttpUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

/**
 * @name 百度云 工具类
 * @author choudou5
 * @date 2018-08-21
 */
public class BdCloudUtil {

    private static final Logger logger = LoggerFactory.getLogger(BdCloudUtil.class);

    private static final LRUCache<String, String> CACHE = CacheFactory.newLRUCache(10, 20*24*60*1000);
    private static final String ACCESS_TOKEN = "access_token";
    private static final Random rd = new Random();

    public static void main(String[] args) {
        String secretId = "Q5MgZCaV6iuDRTKP9BMSgegK";
        String secretKey = "3rzwOUV8reQPFMFlkdiAbDOBs5a33xXi";

        AppKeyBean appKey = new AppKeyBean(secretId, secretKey);
//        getAuth(appKey);

        getTextAnalysis(appKey, "波尔多红酒怎么样");
    }


    /**
     * 获取API访问token  api: http://ai.baidu.com/docs#/Auth/top
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @return assess_token 示例：24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(AppKeyBean appKey) {
        String accessToken = CACHE.get(ACCESS_TOKEN);
        if(StrUtil.isBlank(accessToken)){
            // 获取token地址
            String api = String.format(AnalysisConsts.BAIDU_ACCESS_TOKEN_API, appKey.getSecretId(), appKey.getSecretKey());
            System.out.println(api);
            String resp = HttpUtils.get(api);
            if(StrUtil.isNotBlank(resp)){
                accessToken = JSON.parseObject(resp).getString("access_token");
                if(StrUtil.isNotBlank(accessToken)){
                    CACHE.put(ACCESS_TOKEN, accessToken);
                }else{
                    LogDeBugUtil.debug("获取百度accessToken失败", resp);
                }
            }
        }
        return accessToken;
    }


    public static String getTextAnalysis(AppKeyBean appKey, String text){
        // 初始化一个AipNlp
        AipNlp client = new AipNlp("", appKey.getSecretId(), appKey.getSecretKey());
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(3000);
        // 调用接口
        JSONObject res = client.lexer(text, null);
        System.out.println(res.toString(2));
        return null;
    }


}
